import { ref } from 'vue'

// 从localStorage获取初始值
const getStoredPattern = () => {
  const stored = localStorage.getItem('currentPattern')
  return stored ? JSON.parse(stored) : null
}

// 当前选中的图案
const currentPattern = ref(getStoredPattern())
const lastPattern = ref(null)

// 设置当前图案
const setCurrentPattern = (pattern) => {
  currentPattern.value = pattern
  lastPattern.value = null
  // 保存到localStorage
  if (pattern) {
    localStorage.setItem('currentPattern', JSON.stringify(pattern))
  } else {
    localStorage.removeItem('currentPattern')
  }
  console.log('patternStore: 设置当前图案', {
    patternName: pattern?.name,
    patternCategory: pattern?.category
  })
}

// 切换当前图案
const switchCurrentPattern = () => {
  // 交换当前图案和lastPattern
  const temp = currentPattern.value
  currentPattern.value = lastPattern.value
  lastPattern.value = temp
  localStorage.removeItem('currentPattern')
  localStorage.setItem('currentPattern', JSON.stringify(currentPattern.value))
  console.log('patternStore: 切换当前图案')
}

// 获取当前图案
const getCurrentPattern = () => {
  return currentPattern.value
}

export {
  currentPattern,
  setCurrentPattern,
  switchCurrentPattern,
  getCurrentPattern
} 